package com.cipta.lomob.fragments;

import java.io.IOException;
import java.util.LinkedList;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cipta.lomob.R;
import com.cipta.lomob.adapter.CommentsAdapter;
import com.cipta.lomob.base.BaseFragment;
import com.cipta.lomob.components.VideoControllerView;
import com.cipta.lomob.model.Comments;
import com.cipta.lomob.model.ItemVideo;
import com.cipta.lomob.utils.AspectRatio;
import com.cipta.lomob.utils.SampleData;

public class DetilVideoFragment extends BaseFragment implements SurfaceHolder.Callback, MediaPlayer.OnVideoSizeChangedListener, MediaPlayer.OnPreparedListener, VideoControllerView.MediaPlayerControl {
    SurfaceView videoSurface;
    MediaPlayer player;
    VideoControllerView controller;
    private FrameLayout videoSurfaceContainer;
    private RelativeLayout videoDetailContainer;
	private ListView lvItem;
	private TextView tvTitle;
	private TextView tvWatchingCount;
	private TextView tvLoveCount;
	private ImageButton btnPlayPause, btnReport;
	private ProgressBar indicator, videoProgress;
	private LinkedList<Comments> listComment;
	private boolean isControllingShowing = true;
	private boolean isReady = false;
	private boolean isAutoPlay = false;
	private long lastTouch;
	private ItemVideo video;
	
	//Video STATE
	// -1 = INITIAL
	//  0 = VIDEO HAS PREPARED
	//  1 = VIDEO PLAYABLE
	
	private int VIDEO_STATE = -1;
	//16:9
	private LinearLayout.LayoutParams potraitVideoParams;
	private boolean isPotrait = true;
	
	public DetilVideoFragment(ItemVideo iVideo){
		this.video = iVideo;
	}
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		initializeLibs();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_detail_video, container, false);
		initializeViews(view);
		return view;
	}
	
	@SuppressLint("NewApi")
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		initializeProcess();
		initializeActions();
		
		//setup video here
		SurfaceHolder videoHolder = videoSurface.getHolder();
        videoHolder.addCallback(this);
        player = new MediaPlayer();
        controller = new VideoControllerView(getActivity()); 
        try {
        	String url = "rtsp://103.25.202.151:1935/vods3/_definst_/amazons3/lomob/diving_400x300.mp4";
            player.setAudioStreamType(AudioManager.STREAM_MUSIC);            
            player.setDataSource(getActivity(), Uri.parse(url));//"rtsp://103.25.202.151:1935/vod/_definst_/yoze/yoze.mp4"));
            player.setOnPreparedListener(this);
            player.setOnVideoSizeChangedListener(this);
            
            player.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {            	
				@Override
				public void onBufferingUpdate(MediaPlayer mp, int percent) {
					if(percent <99){
						if(videoProgress.getVisibility() == View.GONE){
							videoProgress.setVisibility(View.VISIBLE);
						}
					}else{
						if(player.isPlaying())
						videoProgress.setVisibility(View.GONE);
					}
				}
			});
            
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
			prepareLandscapeButtons();
		}else{
			preparePotraitButtons();
		}
		
		//this to resize video
		try{
			prepareVideoAspectRation(player.getVideoWidth(), player.getVideoHeight(), getHeight());
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	
	@Override
	public void initializeViews(View view) {
		// TODO Auto-generated method stub
		super.initializeViews(view);
		tvTitle = (TextView) view.findViewById(R.id.inf_txt_header_view_detil_video_title);
		tvWatchingCount = (TextView) view.findViewById(R.id.inf_txt_header_view_detil_video_totalcomments);
		tvLoveCount = (TextView) view.findViewById(R.id.inf_txt_header_view_detil_video_totallikes);
		videoSurfaceContainer = (FrameLayout) view.findViewById(R.id.videoSurfaceContainer);
		videoSurfaceContainer.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, getHeight()));
		potraitVideoParams = (android.widget.LinearLayout.LayoutParams) videoSurfaceContainer.getLayoutParams();
		videoDetailContainer = (RelativeLayout) view.findViewById(R.id.video_detail_container);
		videoSurface = (SurfaceView) view.findViewById(R.id.videoSurface);
		lvItem = (ListView)view.findViewById(R.id.lv_detil_video);
		indicator = (ProgressBar)view.findViewById(R.id.pb_detil_video);
		videoProgress = (ProgressBar) view.findViewById(R.id.progressbar_video);
		btnReport = (ImageButton)view.findViewById(R.id.btn_report);
		btnPlayPause = (ImageButton) view.findViewById(R.id.potrait_pause);
		//add video surface touche event
		videoSurface.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(isPotrait){
					if(event.getAction() == event.ACTION_DOWN){
						togglePotraitVideoController();
					}
				}else{
					controller.show();
				}
				return true;
			}
		});
	}
	
	@Override
	public void initializeProcess() {
		// TODO Auto-generated method stub
		super.initializeProcess();
		//set video information
		listComment = new LinkedList<Comments>();
		Comments comments = null;
		for (int i = 0; i < SampleData.sampleDataItemComments.length; i++) {
			comments = new Comments();
			comments.setComment(SampleData.sampleDataItemComments[i][0]);
			comments.setTime(SampleData.sampleDataItemComments[i][1]);
			comments.setAvatar(SampleData.sampleDataItemCommentsImage[i]);
			
			listComment.add(comments);
		}
		
		CommentsAdapter commentsAdapter = new CommentsAdapter(getActivity(), listComment);
		lvItem.setAdapter(commentsAdapter);
		
		//set detail video info
		tvTitle.setText(video.getTitle());
		tvWatchingCount.setText(String.valueOf(video.getTotalWatching()));
		tvLoveCount.setText(String.valueOf(video.getTotalLove()));
	}
	
	
	
	private void showReportDialog(){
		final Dialog dialog = new Dialog(getActivity());
		dialog.setContentView(R.layout.dialog_report);
		Button btnOk = (Button)dialog.findViewById(R.id.btn_dialog_report_);
		btnOk.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		dialog.show();
	}
	
	@Override
	public void initializeActions() {
		// TODO Auto-generated method stub
		super.initializeActions();
		
		btnReport.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showReportDialog();
			}
		});
		
		btnPlayPause.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//action
				if(!isReady) {
					v.setVisibility(View.GONE);
					videoProgress.setVisibility(View.VISIBLE);
					isAutoPlay = true;
					return;			
				}
				if(player.isPlaying()){
					player.pause();
					//set background
					btnPlayPause.setImageResource(R.drawable.ic_potrait_play);
				}else{
					player.start();
					btnPlayPause.setImageResource(R.drawable.ic_potrait_pause);
					videoProgress.setVisibility(View.GONE);
				}
			}
		});
	}

	   // Implement SurfaceHolder.Callback
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
 
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
    	if(VIDEO_STATE == -1){
        	player.setDisplay(holder);
            player.prepareAsync();
            VIDEO_STATE = 0;
    	}else{
    		
    		player.setDisplay(holder);
    	}
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        
    }

    // Implement MediaPlayer.OnPreparedListener
    @Override
    public void onPrepared(MediaPlayer mp) {
    	isReady = true;
        controller.setMediaPlayer(this);
        controller.setAnchorView(videoSurfaceContainer);
        if(isAutoPlay)
        player.start();
    }
    // End MediaPlayer.OnPreparedListener

    // Implement VideoMediaController.MediaPlayerControl
    @Override
    public boolean canPause() {
        return true;
    }

    @Override
    public boolean canSeekBackward() {
        return true;
    }

    @Override
    public boolean canSeekForward() {
        return true;
    }

    @Override
    public int getBufferPercentage() {
        return 0;
    }

    @Override
    public int getCurrentPosition() {
        return player.getCurrentPosition();
    }

    @Override
    public int getDuration() {
        return player.getDuration();
    }

    @Override
    public boolean isPlaying() {
        return player.isPlaying();
    }

    @Override
    public void pause() {
        player.pause();
    }

    @Override
    public void seekTo(int i) {
        player.seekTo(i);
    }

    @Override
    public void start() {
        player.start();
    }

    @Override
    public boolean isFullScreen() {
        return false;
    }

    @Override
    public void toggleFullScreen() {
        
    }
    // End VideoMediaController.MediaPlayerControl

	@Override
	public void onDestroy() {
		super.onDestroy();
		if(player !=null){
			player.release();
			player = null;
		}
	}

	@Override
	public void onStart() {
		super.onStart();
	}

	@Override
	public void onStop() {
		if(player != null){
			Log.i("Lomob MP", "pause player");
			player.pause();
		}
		super.onStop();
	}
	
	private int getHeight(){
		//screen ratio is 16:9
		Display display = getActivity().getWindowManager().getDefaultDisplay();
		int screenWidth = display.getWidth();		
		int screenHeight = (screenWidth/16) * 9; 
		Log.i("Screen", "height size: " + screenHeight);
		return screenHeight;
	}
	
	private void prepareLandscapeButtons(){
		videoDetailContainer.setVisibility(View.GONE);
		getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		videoSurfaceContainer.setLayoutParams(lp);
		isPotrait = false;
		
		if(btnReport.getVisibility() == View.VISIBLE){
			btnReport.setVisibility(View.GONE);
		}
		
		if(btnPlayPause.getVisibility() == View.VISIBLE){
			btnPlayPause.setVisibility(View.GONE);
		}
	}
	
	private void preparePotraitButtons(){
		videoDetailContainer.setVisibility(View.VISIBLE);
		getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN, WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		videoSurfaceContainer.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, getHeight()));
		isPotrait = true;
		
		if(btnPlayPause.getVisibility() == View.VISIBLE && player.isPlaying()){
			btnPlayPause.setVisibility(View.GONE);
		}else{
			btnPlayPause.setVisibility(View.VISIBLE);
		}
		
		if(btnReport.getVisibility() == View.GONE){
			btnReport.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void reportClick() {
		showReportDialog();
	}
	
	private void prepareVideoAspectRation(int videoWidth, int videoHeight, int screenHeight){
		int newWidth = AspectRatio.findWidht(videoWidth, videoHeight, screenHeight);
		FrameLayout.LayoutParams newParams = new FrameLayout.LayoutParams(newWidth, screenHeight, Gravity.CENTER);
//		videoSurface.setLayoutParams(newParams);
		videoSurface.getHolder().setFixedSize(newWidth, screenHeight);
	}

	@Override
	public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
		   Log.i("Lomob", "Update MP size");
		   prepareVideoAspectRation(width, height, getHeight()); 
	}
	
	private void togglePotraitVideoController(){
		if(isControllingShowing){
			//the controller is showing now so hide controller
			hidePotraitController();
		}else{
			showController();
		}
	}
	
	private void hidePotraitController(){
		btnPlayPause.setVisibility(View.GONE);
		isControllingShowing = false;
	}
	
	private void showController(){
		if(player.isPlaying()){
			btnPlayPause.setImageResource(R.drawable.ic_potrait_pause);
		}else{
			btnPlayPause.setImageResource(R.drawable.ic_potrait_play);
		}
		btnPlayPause.setVisibility(View.VISIBLE);
		isControllingShowing = true;
	}
}
